package api

import (
	"encoding/json"
	"fmt"
	"hello/tools"
	"strconv"
)

type StudentController struct {
	BaseController
}

func (c *StudentController) Get() {
	c.Ctx.WriteString("api student")
}

func (c *StudentController) Index() {
	c.Ctx.WriteString("学生列表接口")
}

func (c *StudentController) GetStudent() {
	// id, err := c.GetString("id")
	id, err := c.GetInt("id")
	if err != nil {
		// fmt.Printf("id必须为数字")
		c.Ctx.WriteString("id必须为数字")
		return
	}
	fmt.Printf("id的值: %v", id)
	c.Ctx.WriteString("学生详情接口")
}

type Student struct {
	Id   int    `form:"id" json:"id"`
	Name string `form:"name" json:"name"`
	Age  int    `form:"age" json:"age"`
}

func (c *StudentController) GetStudentJson() {
	// 返回json数据
	stu := Student{
		Id:   123,
		Name: "lijun",
		Age:  29,
	}

	c.Data["json"] = stu
	c.ServeJSON()
}

func (c *StudentController) GetStudentJson_v2() {
	// 获取post请求数据
	stu := Student{}
	if err := c.ParseForm(&stu); err != nil {
		//handle error
		fmt.Printf("参数有误")
		return
	}
	// c.ParseForm(&stu)
	fmt.Printf("%#v\n", stu)
	fmt.Println(stu.Name)
	c.Data["json"] = stu
	c.ServeJSON()
}

func (c *StudentController) GetStudentJson_v3() {
	//  获取json数据
	stu := Student{}
	json.Unmarshal(c.Ctx.Input.RequestBody, &stu)
	// c.ParseForm(&stu)
	fmt.Printf("%#v\n", stu)
	fmt.Println(stu.Name)
	c.Data["json"] = stu
	c.ServeJSON()
}

func (c *StudentController) Get_timestamp() {
	this_time := tools.GetTimestamp()
	// int64类型转字符串
	this_time_str := strconv.FormatInt(this_time, 10)
	// fmt.Println(this_time)

	c.Ctx.WriteString("时间戳:" + this_time_str)
}

func (c *StudentController) Get_md5() {
	// md5_str := tools.Retrun_md5("123")
	md5_str := tools.Retrun_md5_v2("1234")
	fmt.Println(md5_str)
	c.Ctx.WriteString("md5加密:" + md5_str)
}

func (c *StudentController) BeforeAfter() {

	fmt.Println("请求中处理")
	stu := Student{
		Id:   123,
		Name: "lijun",
		Age:  29,
	}

	c.Data["json"] = stu
	c.ServeJSON()
}
